import {Button, message, Modal, Radio, Tag} from 'antd';
import React, {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import {isSuccess} from "@/utils/utils";
import { OpSpecialManager} from "@/services/api-functions";
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {history} from "@@/core/history";
import {ExclamationCircleOutlined, PlusOutlined} from "@ant-design/icons";
import {SYS_ENUMS} from "@/utils/constants";
import {OssPojo, ResourcesSpecialModRequest} from "@/services/api-types";

export const handleResourceTopicEdit = async (fields: any, select: any, cover: OssPojo | undefined,) => {
  try {
    const rpo: ResourcesSpecialModRequest = {
      id: select?.id ?? '',
      cover,
      content: fields.content,
      title: fields.title,
      endTime: fields.endTime,
      startTime: fields.startTime,
      detailCover: fields.detailCover,
      resourcesIds: fields.resourcesIds,
      state: fields.state,
    }
    if (isSuccess((select && select.id ? (await OpSpecialManager.resourcesEdit(rpo)) : (await OpSpecialManager.specialAdd(rpo)))?.code)) {
      message.success('保存成功');
      return true;
    }
    return false;
  } catch (error) {
    return false;
  }
};

export const handleResourceTopicChangeState = async (id: any, state: 'UP'|'DOWN',) => {
  try {
    if (isSuccess((await OpSpecialManager.specialOperate(id, state))?.code)) {
      message.success('保存成功');
      return true;
    }
    return false;
  } catch (error) {
    return false;
  }
};

export const handleResourceTopicDel = async (id: any) => {
  try {
    if (isSuccess((await OpSpecialManager.specialDel(id))?.code)) {
      message.success('删除成功');
      return true;
    }
    return false;
  } catch (error) {
    return false;
  }
};

const ResourceTopicList: React.FC<any> = (props) => {
  const actionRef = useRef<ActionType>();
  const [state, setState] = useState<'ALL'|'UP'|'DOWN'>('ALL');
  const [countInfo, setCountInfo] = useState<{ALL: number, UP: number, DOWN: number}>({ALL:0, UP: 0, DOWN: 0});
  const columns: ProColumns[] = [
    {
      title: '封面',
      dataIndex: 'cover',
      ellipsis: true,
      hideInSearch: true,
      width: 200,
      fixed: 'left',
      render: (dom, record) => record.cover?<img src={record.cover?.url} alt="" style={{maxWidth:187, maxHeight: 148}}/>:'-',
    },
    {
      title: '专题标题',
      dataIndex: 'title',
      ellipsis: true,
      width: 170
    },
    {
      title: '描述',
      dataIndex: 'content',
      ellipsis: true,
      width: 250,
    },
    {
      title: '排序',
      dataIndex: 'sortNum',
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },{
      title: '专题状态',
      dataIndex: 'state',
      ellipsis: true,
      hideInSearch: true,
      valueEnum: SYS_ENUMS.TOPIC_STATUS,
      width: 120,
    },{
      title: '资源数',
      dataIndex: 'resourcesNum',
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },{
      title: '专题浏览量',
      dataIndex: 'browseNum',
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },{
      title: '发布时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      width: 170,
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      hideInForm: true,
      fixed: 'right',
      render: (_, record) => [
        <a key="edit" href={`/resource/topic/edit/${record?.id}`}>详情</a>,
        <a key="edit" onClick={() => Modal.confirm({
          title: '提示',
          icon: <ExclamationCircleOutlined/>,
          content: <span>确定要{record.state === 'UP'?'禁用':'启用'} <Tag color='#108ee9'>{record.title}</Tag> 吗？</span>,
          okText: record.state === 'UP'?'禁用':'启用',
          cancelText: '取消',
          onOk: async () => {
            if (await handleResourceTopicChangeState(record?.id, record.state === 'UP' ? 'DOWN' : 'UP')) {
              actionRef.current?.reload()
            }
          },
        })}>{record.state === 'UP'?'禁用':'启用'}</a>,
        <a key="edit" onClick={() => Modal.confirm({
          title: '提示',
          icon: <ExclamationCircleOutlined/>,
          content: <span>确定要删除 <Tag color='#108ee9'>{record.title}</Tag> 吗？</span>,
          okText: '删除',
          cancelText: '取消',
          onOk: async () => {
            if (await handleResourceTopicDel(record?.id)) {
              actionRef.current?.reload()
            }
          },
        })}>删除</a>

      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<any, any>
        actionRef={actionRef}
        rowKey="key"
        search={{labelWidth: 120,}}
        headerTitle={<Radio.Group value={state} onChange={(e) => {
          setState(e.target.value)
          actionRef.current?.reload()
        }}>
          <Radio.Button value='ALL'>全部 {countInfo?.ALL ?? 0}</Radio.Button>
          <Radio.Button value='UP'>已启用 {countInfo?.UP ?? 0}</Radio.Button>
          <Radio.Button value='DOWN'>已禁用 {countInfo?.DOWN ?? 0}</Radio.Button>
        </Radio.Group>}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => history.push('/resource/topic/edit')}>
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={async (params) => {

          const query = {...params}

          if (state !== 'ALL') {
            query.state = state;
          }

          const {data, code}: any = await OpSpecialManager.pageQuery(query);

          setCountInfo((await OpSpecialManager.specialManagerCount())?.data)

          return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? data.length : 0};
        }}
        columns={columns}
        scroll={{ x: 1300 }}
      />
    </PageContainer>
  );
};

export default ResourceTopicList;
